<template>
  <div class="activity-management">
    <el-card shadow="never">
      <div class="header">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="活动名称">
            <el-input v-model="queryParams.activityName" placeholder="活动名称" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select style="width: 120px" v-model="queryParams.status" placeholder="状态">
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="轮播图">
            <el-select style="width: 120px" v-model="queryParams.isBanner" placeholder="轮播图">
              <el-option label="启用" value="1" />
              <el-option label="关闭" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        
        <el-button v-permission="['editActivity']" type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon>新增活动
        </el-button>
      </div>
      
      <el-table 
        :data="activities" 
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="activityName" label="活动名称" />
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{row}">
            <el-tag :type="row.status == 1 ? 'success' : 'danger'">
              {{ row.status == 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="轮播图" width="100">
          <template #default="{row}">
            <el-tag :type="row.isBanner == 1 ? 'success' : 'danger'">
              {{ row.isBanner == 1 ? '启用' : '关闭' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" v-permission="['editActivity']">
          <template #default="{row}">
            <el-button size="small" @click="editActivity(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDeleteActivity(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :small="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`${mode === 'add' ? '新增' : '编辑'}活动`"
      width="50%"
      :fullscreen="true"
    >
      <el-form :model="form" ref="formRef" label-width="100px">
        <el-form-item label="活动名称" prop="activityName" required>
          <el-input v-model="form.activityName" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar" required>
          <el-upload class="avatar-uploader" action="/api/upload" :headers="{ 'Authorization': `Bearer ${getToken()}` }"
            :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="form.avatar" :src="form.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="1">启用</el-radio>
            <el-radio value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="轮播图" prop="isBanner">
          <el-radio-group v-model="form.isBanner">
            <el-radio value="1">启用</el-radio>
            <el-radio value="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="'default'"
            />
            <Editor
              style="height: 400px; overflow-y: hidden;"
              v-model="form.description"
              :defaultConfig="editorConfig"
              :mode="'default'"
              @onCreated="handleCreated"
              @onChange="handleChange"
            />
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, shallowRef, onBeforeUnmount } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'
import { 
  getActivityList,
  addActivity,
  updateActivity,
  deleteActivity
} from '@/api/activity'

const editorRef = shallowRef() // wangEditor 编辑器实例
const toolbarConfig = reactive({}) // wangEditor 工具栏配置
const activities = ref([])
const total = ref(0)
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  activityName: '',
  status: '',
  isBanner: ''
})

// 对话框控制
const dialogVisible = ref(false)
const formRef = ref(null)
const mode = ref('add') // 'add' or 'edit'
const currentId = ref(null)

// 表单数据
const form = reactive({
  activityName: '',
  avatar: '',
  description: '',
  status: '1',
  isBanner: '0'
})

// 加载状态
const loading = ref(false)

// 获取活动列表
const fetchActivities = async () => {
  loading.value = true
  try {
    const res = await getActivityList(queryParams)
    activities.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取活动列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.page = 1
  fetchActivities()
}

// 重置查询
const resetQuery = () => {
  queryParams.page = 1
  queryParams.activityName = ''
  queryParams.status = ''
  fetchActivities()
}

// 分页改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchActivities()
}

// 分页改变
const handleCurrentChange = (val) => {
  queryParams.page = val
  fetchActivities()
}

// 初始化加载数据
onMounted(() => {
  fetchActivities()
})

const showAddDialog = () => {
  mode.value = 'add'
  form.activityName = ''
  form.avatar = ''
  form.description = ''
  form.status = '1'
  form.isBanner = '0'
  dialogVisible.value = true
}

// 显示编辑对话框
const editActivity = (row) => {
  mode.value = 'edit'
  currentId.value = row.id
  form.activityName = row.activityName
  form.description = row.description
  form.avatar = row.avatar
  form.status = row.status
  form.isBanner = row.isBanner
  dialogVisible.value = true
}

// 删除活动
const handleDeleteActivity = async (row) => {
  try {
    await ElMessageBox.confirm(`确定删除活动 "${row.activityName}"?`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteActivity({id: row.id})
    ElMessage.success('删除成功')
    await fetchActivities()
  } catch (error) {
    console.error('删除活动失败:', error)
  }
}

// wangEditor 相关
const editorConfig = reactive({
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      fieldName: 'file',
      server: '/api/upload',
      headers: { Authorization: `Bearer ${getToken()}` },
      customInsert(res, insertFn) {
        insertFn(res.data)
      }
    },
    uploadVideo: {
      fieldName: 'file',
      server: '/api/upload',
      headers: { Authorization: `Bearer ${getToken()}` },
      customInsert(res, insertFn) {
        insertFn(res.data)
      }
    }
  }
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const handleChange = (editor) => {
  // console.log('change:', editor.getHtml())
}

onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 提交表单
const submitForm = async () => {
  try {
    if (mode.value === 'add') {
      await addActivity(form)
    } else {
      await updateActivity({
        ...form,
        id: currentId.value
      })
    }
    ElMessage.success(mode.value === 'add' ? '新增成功' : '更新成功')
    dialogVisible.value = false
    await fetchActivities()
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}



// 头像上传成功处理
const handleAvatarSuccess = (response, file) => {
  console.log(response, URL.createObjectURL(file.raw))
  form.avatar = response.data
}

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isImage = file.type.includes('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isImage) {
    ElMessage.error('您上传的不是图片!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
  }
  return isImage && isLt2M
}
</script>

<style scoped>
.activity-management {
  padding: 20px;
}
.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

#editor-container {
  width: 100%;
  border: 1px solid #dcdfe6;
}

/* 编辑器工具栏样式 */
:deep(.w-e-toolbar) {
  border-bottom: 1px solid #dcdfe6 !important;
  background-color: #f5f7fa !important;
}

/* 编辑器内容区样式 */
:deep(.w-e-text-container) {
  border: none !important;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 500px;
  height: audo;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}
</style>
